﻿// ******************************************************************************
// Developed by Oguz Demirel
// Date: March 9, 2010
// ******************************************************************************
namespace BulkListActions
{
    using System.Collections.Specialized;
    using System.Globalization;
    using System.Net;
    using System.Web.UI;
    using Microsoft.SharePoint.WebPartPages;
    using System;
    using System.Text;

    public class Helper
    {
        // This recursive method finds list view web part on SharePoint page
        public static ListViewWebPart FindListView(Control parent)
        {
            ListViewWebPart part = parent as ListViewWebPart;
            if (part != null)
            {
                return part;
            }
            if (parent.Parent == null)
            {
                return null;
            }
            return FindListView(parent.Parent);
        }

        // This method registers jQuery to the page
        public static void RegisterScript(Page page, string clientID, ListViewWebPart lvwp)
        {
            if (!page.ClientScript.IsClientScriptIncludeRegistered("ListItemSelection"))
            {
                page.ClientScript.RegisterClientScriptInclude("ListItemSelection", "/_layouts/ListItemSelection.js");
            }

            string startupScript = string.Format(CultureInfo.InvariantCulture, "$(function(){{ListItemSelection_Init('{0}', 'WebPart{1}');}});",
                                                clientID,
                                                lvwp.Qualifier);

            page.ClientScript.RegisterStartupScript(typeof(SelectItemsAction), clientID, startupScript, true);
        
        }

        // This method checks query string parameters
        public static void CheckQueryString(NameValueCollection queryString)
        {
            // Parse and check qs parameters
            string strList = queryString["List"];
            if (string.IsNullOrEmpty(strList))
                throw new WebException("Required query string parameter 'List' is not defined.");

            string strView = queryString["View"];
            if (string.IsNullOrEmpty(strView))
                throw new WebException("Required query string parameter 'View' is not defined.");

            string referrer = queryString["referrer"];
            if (string.IsNullOrEmpty(referrer))
                throw new WebException("Required query string parameter 'referrer' is not defined.");
        
        }

        public static bool Move(string oldUrl, string newUrl)
        {
            string result = "";
            string webUrl = GetWebURL(oldUrl);
            oldUrl = oldUrl.Substring(webUrl.Length + 1);
            newUrl = newUrl.Substring(webUrl.Length + 1);
            return Move(webUrl, oldUrl, newUrl, out result);
        }

        public static bool Move(string webUrl, string oldUrl, string newUrl, out string result)
        {
            string renameOption = "findbacklinks";
            string putOption = "overwrite,createdir,migrationsemantics";
            bool doCopy = false;
            string method = 
                "method=move+document%3a12.0.4518.1016" + 
                "&service_name=%2f&oldUrl={0}" + 
                "&newUrl={1}&url_list=[]" + 
                "&rename_option={2}" + 
                "&put_option={3}&docopy={4}";
            
            method = String.Format(
                method, 
                oldUrl, 
                newUrl, 
                renameOption, 
                putOption, 
                doCopy.ToString().ToLower());

            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.Credentials = CredentialCache.DefaultCredentials;
                    webClient.Headers.Add("Content-Type", "application/x-vermeer-urlencoded");
                    webClient.Headers.Add("X-Vermeer-Content-Type", "application/x-vermeer-urlencoded");
                    result = Encoding.UTF8.GetString(webClient.UploadData(
                        webUrl + 
                        "/_vti_bin/_vti_aut/author.dll",
                        "POST", Encoding.UTF8.GetBytes(method)));

                    if (result.IndexOf("\n<p>message=successfully") < 0)
                        throw new Exception(result);
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
                return false;
            }
            return true;
        }

        public static string GetWebURL(string url)
        {
            try
            {
                url = url.Substring(0, url.LastIndexOf("/"));
                try
                {
                    using (WebClient webClient = new WebClient())
                    {
                        webClient.Credentials = CredentialCache.DefaultCredentials;
                        webClient.Headers.Add("Content-Type", "application/x-vermeer-urlencoded");
                        webClient.Headers.Add("X-Vermeer-Content-Type", "application/x-vermeer-urlencoded");
                        byte[] data = Encoding.UTF8.GetBytes("method=open+service%3a12.0.4518.1016&service_name=%2f");
                        string result = Encoding.UTF8.GetString(webClient.UploadData(url + "/_vti_bin/_vti_aut/author.dll", "POST", data));

                        if (result.IndexOf("\n<li>status=327684") == -1)
                            return url;
                        throw new Exception();
                    }
                }
                catch
                {
                    return GetWebURL(url);
                }
            }
            catch
            {
                return null;
            }
        }

    }

}
